import java.util.Arrays;
import java.util.Scanner;

/*有一个已经排好序的数组。现输入一个数，要求按原来的规律将它插入数组中。*/
public class Exerise_30 {
    public static void main(String[] args) {
        int array[] = new int[10];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random() * 100);
            for (int j = 0; j < i; j++) {
                if (array[i] == array[j]) {
                    i--;
                    break;
                }
            }
        }
        System.out.print("原数组");
        System.out.println(Arrays.toString(array));
        System.out.print("排序好的数组");
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(array));
        int newArray[] = new int[array.length + 1];
        System.out.println("插入元素之前");
        for (int i = 0; i < array.length; i++) {
            newArray[i] = array[i];
            System.out.print(newArray[i] + " ");
        }
        System.out.println();
      /*  System.arraycopy(array,0,newArray,0,array.length);
        System.out.println(Arrays.toString(newArray));*/
        int num;
        int index=newArray.length;
        System.out.println("输入一个要插入的整数");
        Scanner sc = new Scanner(System.in);
        num = sc.nextInt();
        // 把要插入的元素与数组中的元素进行比较，
        // 如果要插入的元素小于数组中的元素，把当前的下标给index.
        for (int i = 0; i < newArray.length; i++) {
            if (num < newArray[i]) {
            index=i;
            break;
            }
        }

        for (int i = newArray.length-1; i >index ; i--) {
            newArray[i]=newArray[i-1];
        }
        newArray[index]=num;
        System.out.println("插入元素之后");
        System.out.println(Arrays.toString(newArray));
    }
}
